
function two_num(num){
    return parseInt(num) < 10 ? "0"+num : num;
}

var app = new Vue({
    el:"#app",
    data:{
        token:"",
        form:{
            datetime:'',
            name:'',
            mobile:'',
            account:'',
            pwd:'',
            note:'',
            mobileCode:''
        },
        validMobile:{mobile:null,code:null,time:60,timer:null,"text":"获取验证码"},
        shop:{id:0,name:''},
        addressList:[],
        showModel:false,
        showDateTime:false,
        showAddress:false,
        calendar:{
            last:false,
            currentYear:0,
            currentMonth:0,
            currentDay:0,
            year:0,
            month:0,
            day:0,
            tempDay:0,//选择好，还未确定
            tempMonth:0,//选择好，还未确定
            tempYear:0,//选择好，还未确定
            date:[],
        },
        hours:{
            stageName:['上午时段','下午时段','晚上时段'],
            stage:[
                [10,11,12],
                [13,14,15,16,17],
                [18,19,20]
            ],
            currentStage:0,
            currentHour:0
        },
        dialog:{
            show:false,
            msg:'',
            type:'alert',
            callback:null
        },
        orderNav:-1,
        orders:[],
        showOrders:[],

    },
    mounted:function(){
        if(APP_PAGE == 'exchange'){
            this.initExchange();
        }else if(APP_PAGE == 'index'){
            //
        }else if(APP_PAGE == 'orders'){
            this.initOrders();
        }
    },
    methods:{
        // 下一月
        nextMonth:function(){
            this.calendar.month *=1;
            if(this.calendar.month == 12){
                this.calendar.month = 1;
                this.calendar.year +=1;
            }else{
                this.calendar.month += 1;
            }
            this.calendar.month = two_num(this.calendar.month);
            this.freshMonthDays();
        },
        // 上一月
        lastMonth:function(){

            //小于今年等于今年但是小月本月不能选择

            this.calendar.month *=1;

            if(this.calendar.month == 1){

                var month   = 12;
                var year    = this.calendar.year - 1;

            }else{
                var month   = this.calendar.month - 1;
                var year    = this.calendar.year;
            }

            if(year < this.calendar.currentYear || (year == this.calendar.currentYear && month < this.calendar.currentMonth)){
                this.calendar.last = false;
                return;
            }
            this.calendar.last = true;
            this.calendar.year  = year;
            this.calendar.month = two_num(month);
            this.freshMonthDays();
        },
        initIndex:function(){

        },
        initExchange:function(){
            this.addressList = window.shopAddress;
            setTimeout(this.getPosition,5000);

            var time = (new Date()).getTime() + 3 * 24 * 60 * 60 * 1000;
            var dateObj = new Date(time);
            var year=dateObj.getFullYear(),month=dateObj.getMonth(),date=dateObj.getDate();
            this.calendar.currentYear = year;
            this.calendar.currentMonth= month+1;
            this.calendar.currentDay  = date;
            this.calendar.currentTimestamp = Date.parse(year+"/"+(month+1)+"/"+date + " 00:00:01");
            this.calendar.day = date;
            this.calendar.month = month + 1;
            this.calendar.year = year;
            this.calendar.tempDay = date;
            this.calendar.tempMonth = month+1;
            this.calendar.tempYear = year;
            this.freshMonthDays();

            this.recoverForm();
        },

        initOrders:function(){
            this.orders = orders;
            this.filterOrder(-1);
        },
        cacheFrom:function(){
            var data = {
                form:this.form,
                shop:this.shop,
                calendar:this.calendar,
                hours:this.hours
            };
            console.log(data);
            sessionStorage.setItem("formData",JSON.stringify(data));
        },
        recoverForm:function(){
            var data = JSON.parse(sessionStorage.getItem("formData"));
            console.log('--');
            console.log(data);
            if(data){
                this.shop = data.shop;
                this.form = data.form;
                this.calendar = data.calendar;
                this.hours = data.hours;

                sessionStorage.removeItem("formData");
            }
        },
        //计算距离
        getPosition:function(){
            var res = '';
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: (res)=>{
                    console.log(res);
                    var latitude = res.latitude*1; // 纬度，浮点数，范围为90 ~ -90
                    var longitude = res.longitude*1; // 经度，浮点数，范围为180 ~ -180。
                    var speed = res.speed; // 速度，以米/每秒计
                    var accuracy = res.accuracy; // 位置精度

                    var shops = this.addressList;
                    console.log(shops);
                    for(var key in shops){
                        var shop = shops[key];
                        var dis = this.getDisance(latitude,longitude,shop.lat,shop.lon)/1000;
                        dis = dis.toFixed(1)
                        shops[key]['distance'] = dis;
                    }
                    this.addressList = shops;
                },
                fail:(res)=>{
                    console.log(res);
                    //this.myalert("定位获取失败");
                }
            });
        },
        //lat为纬度, lng为经度, 一定不要弄错
        getDisance:function(lat1, lng1, lat2, lng2) {
            if(lat1*lat2*lng1*lng2 == 0){
                return 0;
            }
            function toRad(d) {  return d * Math.PI / 180; }
            var radLat1 = toRad(lat1);
            var radLat2 = toRad(lat2);
            var deltaLat = radLat1 - radLat2;
            var deltaLng = toRad(lng1) - toRad(lng2);

            var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
            return dis * 6378137;

        },
        freshMonthDays:function(){

            var firstDay = this.calendar.year + "/"+this.calendar.month + "/01 00:00:01";
            var timestamp = Date.parse(firstDay);
            var date,week,month,DATE;
            this.calendar.month *= 1;
            var dayTimestamp = 24*60*60*1000;
            var calendar = [];
            var weekDays = [];
            var weekNum  = 0;
            do{
                DATE    = new Date(timestamp);
                date    = DATE.getDate();
                month   = DATE.getMonth() + 1;
                week    = DATE.getDay();
                date    = {
                    date:date,
                    timestamp:timestamp
                };

                if(week == 6 || month != this.calendar.month){   //每周六，开始新的一周

                    if(month == this.calendar.month){
                        weekDays.push(date);
                    }

                    if(weekDays.length < 7){
                        if(weekNum == 0){

                            while(weekDays.length <7){
                                weekDays.splice(0,0,'');
                            }
                        }else{
                            while(weekDays.length < 7){
                                weekDays.push('');
                            }
                        }
                    }

                    calendar.push(weekDays);
                    weekDays = [];
                    weekNum++;
                }else{
                    weekDays.push(date);
                }

                timestamp += dayTimestamp;
            }while(month == this.calendar.month)

            this.calendar.date = calendar;
            this.calendar.month = two_num(this.calendar.month);
        },
        //选择日期
        choiceDate:function(date){
            if(date == ''){
                return;
            }

            if(date < this.calendar.currentDay
                && parseInt(this.calendar.month) == this.calendar.currentMonth
                && this.calendar.year == this.calendar.currentYear
            ){
                return this.myalert("无效日期");
            }

            this.calendar.tempMonth = this.calendar.month;
            this.calendar.tempDay = date;
            this.calendar.tempYear = this.calendar.year;

        },
        //选择日期和时间确定
        setDateTime:function(){
            if(this.hours.currentHour == 0){
                return this.myalert("请选择时间");
            }
            var calendar = this.calendar;
            this.calendar.day = two_num(this.calendar.tempDay);
            this.calendar.year = this.calendar.tempYear;
            this.calendar.month = this.calendar.tempMonth;
            this.form.datetime = (new Array(calendar.year,calendar.month,calendar.day)).join('-');
            this.form.datetime += ' ' + two_num(this.hours.currentHour) + ":00";

            this.closeModel();
        },
        //关闭遮罩
        closeModel:function(){
            this.showModel = false;
            this.showAddress = false;
            this.showDateTime = false;
        },
        dialogCallback:function(res){
            if(res == true && this.dialog.type == 'confirm')
            {
                this.dialog.callback();
            }
            this.dialog.show = false;
        },
        myalert:function(msg){
          this.dialog.show = true;
          this.dialog.type = 'alert';
          this.dialog.msg = msg;
        },
        myconfirm:function(msg,callback){
            this.dialog.show = true;
            this.dialog.type = 'confirm';
            this.dialog.msg = msg;
            this.dialog.callback = callback;
        },
        test:function(){
            console.log('ok');
        },
        choiceShop:function(shop){
            this.shop = shop;
            this.closeModel();
        },
        checkExchangeData:function(){
            //检查信息
            var end = function(){event.preventDefault();}
            if(this.shop.id == 0)
            {
                this.myalert("请选择门店");
                return end();
            }
            var data = this.form;
            if(data.dateTime == ''){
                this.myalert("请选择日期和时间");
                return end();
            }

            if(data.name == ''){
                this.myalert("请填写姓名");
                return end();
            }

            if(!(/^1[3456789]\d{9}$/.test(data.mobile))){
                this.myalert("请先写合格的手机号")
                return end();
            }

            if(data.mobileCode == ''){
                this.myalert("请填写验证码");
                return end();
            }

            if(!this.checkMobileCode()){
                this.myalert("验证码错误");
                return end();
            }
            return true;
        },
        checkCardValid:function(){
            var end = function(){event.preventDefault();}
            if(this.form.account == ''){
                this.myalert("卡号不能为空");
                return end();
            }

            if(this.form.pwd == ''){
                this.myalert("密码不能为空");
                return end();
            }
            var res = null;
           $.ajax({
               url:"./checkCard",
               type:'get',
               async:false,
               data:{account:this.form.account,pwd:this.form.pwd},
               success:function(result){
                    res = result;
               }
           })
            if(res.code == 200){
               return true;
            }
            this.myalert(res.msg);
            return end();
        },
        filterOrder:function(type){
            this.orderNav = type;
            if(type < 0){
                this.showOrders = this.orders;
            }else{
                var o = [];
                for(order of this.orders)
                {
                    if(order.status == type){
                        o.push(order);
                    }
                }
                this.showOrders = o;
            }
        },
        sendMobileCode:function(){

            if(this.validMobile.time < 60)
            {
                return ;
            }

            if(!(/^1[3456789]\d{9}$/.test(this.form.mobile)))
            {
                return this.myalert("请先写合格的手机号");
            }
            var url = "./sendCode";
            $.ajax({
                url:url,
                type:'get',
                data:{mobile:this.form.mobile},
                success:(res)=>{
                    if(res.code != 200){
                        this.myalert(res.msg);
                        return;
                    }
                    this.validMobile.mobile = this.form.mobile;
                    this.validMobile.code   = res.mobileCode;
                    this.validMobile.timer  = setInterval(()=>{
                        this.validMobile.time -= 1;
                        this.validMobile.text = this.validMobile.time + "秒后重发";
                        if(this.validMobile.time == 0){
                            clearInterval(this.validMobile.timer);
                            this.validMobile.text = "重新获取";
                            this.validMobile.time = 60;
                        }
                    },1000);
                }
            })
        },
        checkMobileCode:function(){
            var data = {
                mobile:this.form.mobile,
                code:this.form.mobileCode
            };
            var isRight = false;
            $.ajax({
                url:'./checkCode',
                data:data,
                type:'get',
                async:false,
                success:(res)=>{
                    if(res.code == 200){
                        isRight = true;
                    }
                }
            });
            return isRight;
        }
    }
})